<?php

namespace App\Models\XS;

use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use XS;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

//基础迅搜对象
class CmsXS extends XS
{
    //开启缓冲区最小更新总数
    protected static $OPEN_BUFFER_COUNT = 10;

    /** cid空格拼接
     * @param $value
     * @param $key
     * @return string
     */
    public static function implodeCid($value, $key)
    {
        $data = [];
        for ($i = 1; $i < 6; $i++) {
            $num_key = $key . $i;
            $cid = $value->$num_key;
            if ($cid == 0) continue;
            $data[] = $cid;
        }
        return implode(' ', array_unique($data));
    }

    /** 拼接一个cid和pid
     * @param $cid
     * @return string
     */
    public static function implodeOneCidAndPid($cid)
    {
        if ($cid == 0) return $cid;
        return self::pidWithCid($cid);
    }

    /** 拼接多个个cid和pid
     * @param $value
     * @param $key
     * @return string
     */
    public static function implodeManyCidAndPid($value, $key)
    {
        $data = [];
        for ($i = 1; $i < 6; $i++) {
            $num_key = "$key$i";
            $cid = intval($value->$num_key);
            if ($cid == 0) continue;
            $data[] = self::pidWithCid($cid);
        }
        return implode(' ', $data);
    }

    public static function pidWithCid($cid, $str = ' ')
    {
        if ($cid > 9999999) {//是个八位数字
            $pid = intval($cid / 100);
            return (intval($pid / 100) * 100) . $str . $pid . $str . $cid;
        } elseif ($cid % 100 != 0) {//第三级
            return (intval($cid / 100) * 100) . $str . $cid . $str . $cid;//pid
        }
        //1,2级
        return $cid . $str . $cid . $str . $cid;//pid
    }

    /** 拆分出多个cid和pid
     * @param $value
     * @param $key
     * @return array
     */
    public static function explodeManyCidAndPid($value, $key)
    {
        $data = explode(' ', $value);
        $cidArr = [];
        for ($i = 1; $i < 6; $i++) {
            $cidArr["$key$i"] = empty($data[3 * $i - 1]) ? '' : $data[3 * $i - 1];
        }
        return $cidArr;
    }

    protected $cms_curPage;//当前第几页
    protected $cms_perPage;//一页个数

    /** 工作地区转成搜索条件
     * @param $jobArea
     * @param string $k
     * @return string
     */
    public function jobAreaToQuery($jobArea, $k = 'location')
    {
        $values = $jobArea;
        //不是数组,转为数组
        $values = is_array($values) ? $values : explode(',', $values);
        $area = [];
        foreach ($values as $item) {
            $area[] = "$k:$item";

            //找出当前cid的pid不限
            if ($item > 9999999) {
                $pid = intval($item / 100);
                $v = self::pidWithCid($pid);
                $area[] = "$k:\"$v\"";
                //pid的pid
                $v = self::pidWithCid(intval($pid / 100) * 100);
                $area[] = "$k:\"$v\"";
            } elseif ($item % 100 != 0) {
                $v = self::pidWithCid(intval($item / 100) * 100);
                $area[] = "$k:\"$v\"";
            }
        }
        return '(' . implode(' OR ', array_unique($area)) . ') ';
    }

    /**
     * 工作岗位cid转为中文搜索条件,全文检索
     * @param $jobSort
     * @return string
     */
    public function jobSortToQuery($jobSort)
    {
        $values = $jobSort;
        //不是数组,转为数组
        $values = is_array($values) ? $values : explode(',', $values);
        $arr = \DB::table('coll_position')
            ->whereIn('cid', $values)->pluck('name');
        return '(' . implode(' OR ', $arr) . ') ';
    }

    /** 基本分页
     * @param $data
     * @return LengthAwarePaginator
     */
    public function paginate($data)
    {
        return new LengthAwarePaginator($data['data'], $data['total'], $this->cms_perPage, $this->cms_curPage, [
            'path' => Paginator::resolveCurrentPath()
        ]);
    }

    /** 简单分页
     * @param $data
     * @return Paginator
     */
    public function simplePaginate($data)
    {
        return new Paginator($data['data'], $this->cms_perPage, $this->cms_curPage, [
            'path' => Paginator::resolveCurrentPath()
        ]);
    }

    /**
     * 计算两组经纬度坐标 之间的距离
     * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km);
     * return m or km
     */
    public function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
    {
        $earthRadius = 6378.137;//地球半径
        $pi = 3.1415926;
        $radLat1 = $lat1 * $pi / 180.0;
        $radLat2 = $lat2 * $pi / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * $pi / 180.0) - ($lng2 * $pi / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $earthRadius;
        return $s;
    }

    private $cms_log;//日志对象

    public static $cms_job_path = 'xs_job';
    public static $cms_resume_path = 'xs_resume';

    public function logXS($message, $bool = true)
    {
        $file = $bool ? self::$cms_job_path : self::$cms_resume_path;

        if (is_null($this->cms_log)) {
            $this->cms_log = new Logger('xunSearch');
            //按照天,来分组日志
            $path = storage_path('logs/xs/' . $file . '/' . date('Y-m-d', time()) . '.log');
            $this->cms_log->pushHandler(new StreamHandler($path, Logger::INFO, true, 0777));
        }

        $this->cms_log->addInfo($message);
    }

    /** 任务调度日志
     * @param $message
     * @param bool|true $bool
     */
    public function logXSDaily($message, $bool = true)
    {
        $file = $bool ? self::$cms_job_path : self::$cms_resume_path;

        if (is_null($this->cms_log)) {
            $this->cms_log = new Logger('xunSearchDaily');
            //按照天,来分组日志
            $path = storage_path("logs/xs/$file.log");
            $handler = new RotatingFileHandler($path, 3, Logger::INFO, true, 0777);
            $handler->setFormatter(new LineFormatter(null, null, true, true));
            $this->cms_log->pushHandler($handler);
        }

        $this->cms_log->addInfo($message);
    }
}
